package com.zhf.demo03.dao;

import com.zhf.demo03.bean.User;
import com.zhf.demo03.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/10/15 23:26
 */
public class UserDaoImp implements UserDao {
    @Override
    public User userLogin(User user) {
        String password=user.getPassword();
        String username=user.getUserName();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //获取数据库连接
            connection = DbUtil.getConnection();
            //准备SQL语句
            String sql="select * from t_user where userName = ? and password = ?";
            //执行SQL语句
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            resultSet = preparedStatement.executeQuery();
            //查找成功
            if (resultSet.next()){
                User tu=new User(resultSet.getString("userName"),resultSet.getString("password"));
                return  tu;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            DbUtil.closeResource(connection,preparedStatement);
            if (resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;//查找失败
    }
}
